<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>10_ComponentLife</title>
</head>
<body>
<div id="example"></div>

<script src="../../lib/js/react.development.js"></script>
<script src="../../lib/js/react-dom.development.js"></script>
<script src="../../lib/js/babel.min.js"></script>
<script type="text/javascript" src="../../lib/js/prop-types.js"></script>
<script type="text/babel">
  /*
  需求: 自定义组件
    1. 让指定的文本做显示/隐藏的动画
    2. 切换时间为2S
    3. 点击按钮从界面中移除组件界面
   */
  class Life extends React.Component {

    constructor (props) {
      super(props)

      // 初始化状态
      this.state = {
        opacity: 1
      }

      this.distroyComponent = this.distroyComponent.bind(this)
    }

    distroyComponent () {
      ReactDOM.unmountComponentAtNode(document.getElementById('example'))
    }

    componentWillMount () {
      console.log('componentWillMount()')
    }
    componentDidMount () {
      console.log('componentDidMount()')
      // 启动循环定时器
      this.intervalId = setInterval(function () {
        console.log('定时器执行...')
        let {opacity} = this.state
        opacity -= 0.1
        if(opacity<=0) {
          opacity = 1
        }
        this.setState({opacity})
      }.bind(this), 200)
    }

    componentWillUpdate () {
      console.log('componentWillUpdate()')
    }

    componentDidUpdate () {
      console.log('componentDidUpdate()')
    }

    componentWillUnmount () {
      console.log('componentWillUnmount()')
      // 清理定时器
      clearInterval(this.intervalId)
    }


    render () {
      console.log('render()')
      const {opacity} = this.state
      return (
        <div>
          <h2 style={{opacity: opacity}}>{this.props.msg}</h2>
          <button onClick={this.distroyComponent}>不活了</button>
        </div>
      )
    }
  }

  ReactDOM.render(<Life msg="react太难了!"/>, document.getElementById('example'))

</script>
</body>
</html>
